# 国际化模块
import http.client
import hashlib
import urllib
import random
import json
import codecs


class I18n():
  def __init__(self, language_config_path, translate_list_path):
    self.number = 0
    self.language_config = self.read_file(language_config_path)
    self.translate_list = self.read_config(translate_list_path) #是一个列表,存放着要翻译的目标语言,要翻译的文本数量与翻译后的json对象


  def read_file(self, file_path):
    try:
      with open(file_path, encoding='utf8') as file_object:
        return json.loads(file_object.read())
    except Exception as err:
        print('read_file发生错误:', err)

  def read_config(self,file_path):
    _list = []
    try:
      with open(file_path, encoding='utf8') as file_object:
        _file_object = file_object.read()
        for key,value in json.loads(_file_object).items():
          # print( key)
          # print( value)
          # target_language 要翻译成何种语言
          # count 要翻译的文本数量
          # target_obj 存放翻译后的json对象的对象,这里使用的是源语言的格式来初始化,这样我就不用自己构建格式,只需要查找并替换就可以了
          _dict = {'target_language':key,'count':self.count( self.language_config,key),'target_obj':self.language_config}
          # _dict = {'target_language':key,'count':self.count( self.language_config,key)}
          self.number =  0
          _list.append(_dict)
        return _list
    except Exception as err:
        print('read_config发生错误:', err)

  def get_language_config(self):
    return self.language_config

  def get_translate_list(self):
    return self.translate_list

  # 计算要翻译的文字的数量,以提供在何时写入文件的信息
  def count(self, list,target_language):
    for value in list.values():
      if isinstance(value,dict):
          self.count(value,target_language)
      else:
        # print(value)
        # print(self.number)
        self.number = self.number + 1
          
   
    return self.number

  def ergodic(self, list, target_language,index_key=''):
    for key,value in list.items():
      if isinstance(value,dict):
        if index_key=='':
          index_key = key
        else:
          index_key = index_key+ '_' + key
        self.ergodic(value,target_language,index_key)
        index_key = ''
      else:
        key_path = index_key+'_'+key
        for item in self.translate_list:
          if target_language==item['target_language']:
            self.translate(key_path,value,'zh',target_language)
    return 1

  def translate(self,key_path,value,fromLang,toLang):
    appid = ''  # 你的appid
    secretKey = ''  # 你的密钥
    httpClient = None
    myurl = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
    q = value
    salt = random.randint(32768, 65536)

    sign = appid+q+str(salt)+secretKey
    m1 = hashlib.md5()
    m1.update(sign.encode('utf8'))
    sign = m1.hexdigest()
    myurl = myurl+'?appid='+appid+'&q=' + \
        urllib.parse.quote(q)+'&from='+'auto'+'&to='+toLang + \
        '&salt='+str(salt)+'&sign='+sign
    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)
        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result = json.loads(response.read().decode())
        for item in result['trans_result']:
          print(item['src']+'-'+item['dst'])
          self.update(key_path,item['dst'],toLang)
    except Exception as err:
        print('translate发生错误:', err)
    finally:
        if httpClient:
            httpClient.close()
    return 1
    
  def update(self,key_path,text,target_language):
    temp_target_obj = {}
    for item in self.translate_list:
      if target_language==item['target_language']:
        key_path_len = len(key_path.split('_'))
        count = 0
        temp_target_obj = item['target_obj']
        for key_path_item in key_path.split('_'):
          count = count + 1
          if(key_path_len == count):
            temp_target_obj[key_path_item] = text
            break
          temp_target_obj = temp_target_obj[key_path_item]

        item['count'] = item['count'] - 1
        if item['count'] == 0:
          print(item['count'])
          self.file_write(target_language)
    return 1

  #def file_write(self,key_path,target_language,text='测试文本'):
  def file_write(self,target_language='',text='测试文本'):
    # for item in self.translate_list:
    #   if target_language == item['target_language']:
    #     key_path_split = key_path.split('_')
    #     for key_path_item in key_path_split:
    #       item[key_path_item]

    for item in self.translate_list:
      if target_language==item['target_language']:
        print('写入中')
        # print(item['target_obj'])
        filepath = './' + target_language + '.js'
        with codecs.open(filepath,'w',encoding='utf8') as file_object:
          # print(json.dumps(item['target_obj']))
          file_object.write('export const '+target_language+'='+json.dumps(item['target_obj']))
        # print('text')
        # print(text)

    # filepath = './test.json'
    # with open(filepath,'w') as file_object:
    #   file_object.write(text)
    return 1


  # def find_target_language():
  #   for item in self.translate_list:
  #     if target_language==item['target_language']:
  #       return item['target_language']